package smart4j.framework.util;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @author XuYunXuan
 * @ClassName: JsonUtil
 * @Description:
 * @date 2017-09-21 20:03
 */
public class JsonUtil {

    public static final Logger LOGGER = LoggerFactory.getLogger(JsonUtil.class);

    public static final ObjectMapper OBJECT_MAPPER = new ObjectMapper();

    /**
     * pojo to json
     */
    public static <T> String toJson(T obj){
        String json;
        try {
            json = OBJECT_MAPPER.writeValueAsString(obj);
        } catch (Exception e) {
            LOGGER.error("pojo转换json失败",e);
            throw new RuntimeException(e);
        }
        return json;
    }

    /**
     * json to pojo
     */
    public static <T> T fromJson(String json,Class<T> type){
        T pojo;
        try {
            pojo = OBJECT_MAPPER.readValue(json,type);
        } catch (Exception e) {
            LOGGER.error("json转换pojo失败",e);
            throw new RuntimeException(e);
        }
        return pojo;
    }


}
